package gl.java.mq;

import gl.java.umsp.*;
import io.netty.channel.*;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

@ChannelHandler.Sharable
public class Producer extends SimpleChannelInboundHandler<UmspHeader> {

    NettyClient mNet = new NettyClient();


    private volatile Channel mChannel;
    private Queue<Packet> queue = new ConcurrentLinkedQueue<Packet>();

    public void channelActive(final ChannelHandlerContext ctx) throws InterruptedException {
        this.mChannel = ctx.channel();
        while (!queue.isEmpty()) {
            Packet poll = queue.poll();
            NettyMsgHelper.sendPublishMsg(poll, this.mChannel);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, UmspHeader umspHeader) throws Exception {
    }

    private final String mHost;
    private final int mPort;
    private static Logger log = LoggerFactory.getLogger(Consumer.class);

    public Producer(String host, int port) {
        this.mHost = host;
        this.mPort = port;
    }

    public void start() {
        new NettyClient().start(mHost, mPort, this);
    }


    public void publish(String topic, String msg) {
        JSONObject object = new JSONObject();
        queue.add(new Packet(topic, msg));
        if (this.mChannel != null && this.mChannel.isWritable()) {
            while (!queue.isEmpty()) {
                NettyMsgHelper.sendPublishMsg(queue.poll(), this.mChannel);
            }
        }
    }

}
